 var net = require('net');

 var server = net.createServer();

 var sockets = [];

 server.on('connection', function(socket) {

     console.log('got a new connection');

     sockets.push(socket);

     console.log('sockets length:', sockets.length);

     var jsonData = "";
     var beginCount = 0;
     var closeCount = 0;
     var state = "default";
     var client = net.Socket();
     var isConnect = false;
     var preDatas = [];
     var ip = "";
     var port = 0;
     var timeout = 0;
     var handleStart = function() {
         state = "proxy";
         setTimeout(function () {
            console.log("timeout completed"); 
            socket.end();
            client.end();
         }, timeout)
         /* 设置连接的服务器 */
        client.connect(port, ip, function () {
             if (preDatas.length) {
                 for (var i = 0; i < preDatas.length; ++i)
                 {
                     client.write(preDatas[i]);
                 }
                 preDatas = [];
             }
             isConnect = true;
        })
        /* 监听服务器传来的data数据 */
        client.on("data", function (data) {
            //console.log("the data of server is " + data.toString());
            // 如果准备好了  执行shell 命令 mstsc.exe /v:127.0.0.1:4004
            // 如果没好 提示当前列表 和预计等待时间
            // 若有人退出 则更新当前列表 和 等待时间
            socket.write(data);
        })

        /* 监听end事件 */
        client.on("end", function () {
            console.log("data end");
        })
        client.on("close",function(){
            console.log("socket close");
          
        });
        console.log("connect to target",ip,port);
     }
     var handleJson = function(data)
     {
         console.log('got',data)
         var msg = JSON.parse(data);
         console.log(msg);
         if (msg.msgtype == "start")
         {
             handleStart();
         }
         else if (msg.msgtype == "request")
         {
             ip = msg.ip;
             port = msg.port;
             timeout = msg.timeout;
             console.log("start to proxy",ip,port,timeout);
         }
     }
     var toBytes = function(data) {
         var bytes = [];
         var buff = Buffer.from(data)
         for(var i= 0; i< buff.length; i++){
           var byteint = buff[i];
           bytes.push(byteint);
         }
         return bytes;

     }
     var handleData = function(data)
     {
         data = data.toString();
         for (var i = 0; i < data.length;i++)
         {
             jsonData += data[i];
 
 
             if (data[i] == '{')
             {
                 beginCount ++;
             }
             if (data[i] == '}')
             {
                 closeCount++;
             }

             if (beginCount != 0 && beginCount == closeCount)
             {
                 handleJson(jsonData);
                 jsonData = "";
                 beginCount = 0;
                 closeCount = 0;
             }
             
         }
     }
     socket.on('data', function(data) {
         if (state == "proxy")
         {
             // 创建到远程的链接
             /* 创建TCP客户端 */
             if (isConnect)
                client.write(data);
             else
                preDatas.push(data);
             return;
         }
         
         handleData(data);
     });

     socket.on('close', function() {
         console.log('connection closed');
         var index = sockets.indexOf(socket);
         sockets.splice(index, 1);
         console.log('sockets length:', sockets.length);
         // 同步列表信息
     });
     socket.on('error',(err)=>{
         console.log(err);
         var index = sockets.indexOf(socket);
         sockets.splice(index, 1);
         console.log('sockets length:', sockets.length);
          // 同步列表信息
     });

 });

 server.on('error', function(err) {
     console.log('Server error:', err.message);
 });

 server.on('close', function() {
     console.log('Server closed');
 });

 server.listen(4001);
